import * as React from 'react';
import PropTypes from 'prop-types';
import { store } from 'pages/index';

export default class LazyLoadModule extends React.Component {
  constructor() {
    super();
    this.state = {
      module: null,
    };
  }

  componentDidCatch(error) {
    this.setState({ hasError: error });
  }

  componentDidMount() {
    try {
      const { reducers } = this.props;
      if (Array.isArray(reducers)) {
        for (let i = 0; i < reducers.length; i += 1) {
          this.register(reducers[i]);
        }
      } else {
        this.register(reducers);
      }
      this.setState({
        module: true,
      });
    } catch (error) {
      this.setState({ hasError: error });
    }
  }

  componentWillUnmount() {
    // const { reducers = [] } = this.props;
    // reducers.forEach(obj => {
    //   this.unRegister(obj);
    // });
  }

  register = (opt) => {
    const { name, reducer } = opt;
    if (name && store && reducer) {
      store.registerDynamicModule({ name, reducer });
    }
  };

  unRegister = (opt) => {
    const { name } = opt;
    if (store && name) store.unRegisterDynamicModule(name);
  };

  render() {
    const { module, hasError } = this.state;
    if (hasError) return <div>{hasError.message}</div>;
    if (!module) return null;
    if (this.props.component) {
      const Component = this.props.component;
      return <Component {...this.props.props} />;
    }

    return <div>Module loaded</div>;
  }
}

LazyLoadModule.contextTypes = {
  store: PropTypes.object,
};
